/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2023. All rights reserved.
 *
 */

import { SDK_COMPONENTS } from '../const/sdk-const.js';
import { ProjectBuildProfile } from '../options/build/project-build-profile.js';

import { HosSdkInfo } from './info/hos-sdk-info.js';
import { OhosSdkInfo } from './info/ohos-sdk-info.js';
import { Property } from './lib/property-get.js';
import { SdkInfo } from './sdk-info.js';

export class SdkLoader {
  isOhos = false;
  apiMeta: ProjectBuildProfile.ApiMeta;
  static loader?: SdkLoader;
  sdkInfo?: SdkInfo;

  private constructor(apiMeta: ProjectBuildProfile.ApiMeta, isOhos = false) {
    this.isOhos = isOhos;
    this.apiMeta = apiMeta;
  }

  static getSdkInfo(apiMeta: ProjectBuildProfile.ApiMeta, isOhos = false) {
    if (!this.loader) {
      this.loader = new SdkLoader(apiMeta, isOhos);
    }
    if (this.loader.sdkInfo && this.loader.isOhos === isOhos && this.apiCompare(apiMeta, this.loader.apiMeta)) {
      return this.loader.sdkInfo;
    }
    const property: Property = new Property(!this.loader.isOhos);
    const dir = this.loader.isOhos ? property.getSdkDir() : property.getHosSdkDir();
    const sdkInfo = isOhos ? new OhosSdkInfo(SDK_COMPONENTS, apiMeta, dir) : new HosSdkInfo(SDK_COMPONENTS, apiMeta, dir);
    this.loader.sdkInfo = sdkInfo;
    this.loader.isOhos = isOhos;
    this.loader.apiMeta = apiMeta;
    return sdkInfo;
  }

  private static apiCompare(apiMeta: ProjectBuildProfile.ApiMeta, currentSdk: ProjectBuildProfile.ApiMeta) {
    return apiMeta.api === currentSdk.api && apiMeta.version === currentSdk.version && apiMeta.type === currentSdk.type;
  }
}
